import React, { PureComponent } from 'react';
// 引入样式
import './weather.scss'
// 发送axios
import Axios from 'axios';
// 引入接口
import { webSite } from '../../website'
import { message, Input, Button } from 'antd';
export default class Weather extends PureComponent {
  constructor() {
    super()
    this.state = {
      province: '定位中',
      city: '',
      isCity: false,
      input: ''
    }
    // 天气数据
    this.weather = {}
  }
  componentDidMount () {
    const _this = this;
    // 引入挂载在window下的BMap方法
    const { BMap } = window
    // 用于定位
    let geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function getinfo (position) {
      let province = position.address.province;
      let city = position.address.city;
      // 当前所在省市
      // 拿到位置之后
      _this.setState({
        province
      })

      if (!city) {
        _this.setState({
          city: '北京市',
          isCity: false
        })
      } else {
        _this.setState({
          city,
          isCity: true
        })
      }
      // 发送请求
      Axios.create({
        baseURL: `${webSite}:3003`
      }).post("/lifeWeather", { weather: _this.state.city }).then(err => {
        if (err.data.code === 'F0005') {
          // 请求到的天气数据
          _this.weather = err.data.data.result;
          _this.forceUpdate();
          return;
        }
        alert('今天的可用请求次数为0，请明天再试！！！')
      }).catch(() => {
        message.error({ content: '网络较差', className: 'bulletChatMessage' });
      })
    }, function (e) {
      alert("定位失败，请同意获取您的位置信息");
    });
  }

  // 根据不同的天气加载不同的背景(大图)
  isBackground = (weather) => {
    if (weather.indexOf('雨') !== -1) {
      return 'life_weather rain';
    } else if (weather.indexOf('云') !== -1) {
      return 'life_weather cloud';
    } else if (weather.indexOf('晴') !== -1) {
      return 'life_weather Fine';
    }
    return 'life_weather Fine';
  }

  // 根据不同的天气加载不同的背景(小图)
  isBackgroundmia = (weather) => {
    if (weather.indexOf('雨') !== -1) {
      return 'life_weather_data_li rain';
    } else if (weather.indexOf('云') !== -1) {
      return 'life_weather_data_li cloud';
    } else if (weather.indexOf('晴') !== -1) {
      return 'life_weather_data_li Fine';
    }
    return 'life_weather_data_li Fine';
  }
  // input的输入事件
  handleInput = ({ target }) => {
    let { name, value } = target
    // 设置input和state同步
    this.setState({
      [name]: value
    })
  }
  // 查询按钮的事件
  ClickWeather = () => {
    const _this = this;
    let input = this.state.input.replace(/\s+/g, "");
    if (!input) {
      message.error({ content: '请输入查询内容', className: 'bulletChatMessage' });
      return;
    }
    // 发送请求
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/lifeWeather", { weather: input }).then(err => {
      if (err.data.data.reason === '暂不支持该城市') {
        message.error({ content: '暂不支持您输入的地点', className: 'bulletChatMessage' });
        return;
      }
      if (err.data.code === 'F0005') {
        // 请求到的天气数据
        _this.weather = err.data.data.result;
        _this.forceUpdate();
        return;
      }
    }).catch(() => {
      message.error({ content: '网络较差', className: 'bulletChatMessage' });
    })
  }

  // 内容函数
  isWea = () => {
    return (
      <React.Fragment>
        <h2>当前所在城市为：{this.state.province}、{this.state.isCity ? this.state.city : <span style={{ display: 'block', fontSize: '10px' }}>无法获取详细市级单位，默认显示北京天气</span>}</h2>
        <span style={{ color: '#9195A3' }}>定位数据来源自百度地图，可能与真实位置有所偏差，您也可以手动输入位置进行搜索</span>
        {/* 实时数据 */}
        <div className={this.isBackground(this.weather.future[0].weather)}>
          <h2>{this.weather.future[0].date}  {this.weather.city}实时天气</h2>
          <div className='life_weather_du'>
            <div className='life_weather_left'>
              {this.weather.realtime.temperature}
            </div>
            <div className='life_weather_right'>
              <b>°C</b>
              <b>{this.weather.realtime.info}（实时）</b>
            </div>
          </div>
          <h3>{this.weather.future[0].temperature}</h3>
          <h3>{this.weather.future[0].weather}</h3>
          <h3>{this.weather.realtime.direct}</h3>
          <div className='life_weather_duhsu'>{this.weather.realtime.aqi}良</div>
        </div>
        {/* 后几天数据 */}
        <ul className='life_weather_data'>
          {
            this.weather.future.slice(1).map((data, index) => {
              return (
                <li key={data.date} className={this.isBackgroundmia(data.weather)}>
                  <h4 style={{ marginBottom: '30px' }}>
                    {data.date}
                  </h4>
                  <h4>
                    {data.temperature}
                  </h4>
                  <h4 style={{ height: '44px' }}>
                    {data.weather}
                  </h4>
                  <h4 style={{ height: '44px' }}>
                    {data.direct}
                  </h4>
                  <div className='life_weather_duhsu'>{data.wid.day}良</div>
                </li>
              )
            })
          }
        </ul>
        {/* 搜索城市天气 */}
        <span>输入要查询的城市，仅支持查询市级城市比如：北京市、天津市、运城市~</span>
        <div className='weather_top'>
          <Input placeholder="要查询的城市名称" className='weather_input' value={this.state.input} name='input' onChange={this.handleInput} autoComplete="off" maxLength='20' />
          <Button type="primary" className='weather_botton' onClick={this.ClickWeather}>查询</Button>
        </div>
      </React.Fragment>
    )
  }
  render () {
    return (
      <div className='weather'>
        {
          this.weather.city === undefined ? '天气请求正在加载中~' : this.isWea()
        }
      </div>
    )
  }
}